package com.xin.data.simbapesa.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.core.content.ContextCompat;
import androidx.viewbinding.ViewBinding;

import com.google.gson.JsonObject;
import com.xin.data.simbapesa.PathMaping;
import com.xin.data.simbapesa.SimbaApp;
import com.xin.data.simbapesa.activity.SimbaApplyActivity;
import com.xin.data.simbapesa.activity.SimbaCustomerServiceActivity;
import com.xin.data.simbapesa.activity.SimbaPermissionDesActivity;
import com.xin.data.simbapesa.api.PU;
import com.xin.data.simbapesa.api.RxHttp;
import com.xin.data.simbapesa.api.U;
import com.xin.data.simbapesa.base.BaseActivity;
import com.xin.data.simbapesa.base.BaseDialog;
import com.xin.data.simbapesa.base.BaseFragment;
import com.xin.data.simbapesa.base.BaseParams;
import com.xin.data.simbapesa.databinding.SimbaState1FragmentBinding;
import com.xin.data.simbapesa.obj.SimbaProductsAmount;
import com.xin.data.simbapesa.utils.AESCryptUtilJar;
import com.xin.data.simbapesa.utils.JsonParse;
import com.xin.data.simbapesa.utils.LogUtil;
import com.xin.data.simbapesa.utils.NumUtils;
import com.xin.data.simbapesa.utils.SpUtils;
import com.xin.data.simbapesa.utils.ViewUtils;

import java.util.HashMap;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;

public class StateFragment1 extends BaseFragment<SimbaState1FragmentBinding> {


    BaseActivity<ViewBinding> mActivity;

    OnRefreshState1Listener mOnRefreshDataFragmentListener;

    SimbaProductsAmount productsAmount;


    @Override
    public void onAttach(@androidx.annotation.NonNull Context context) {
        super.onAttach(context);
        try {
            mOnRefreshDataFragmentListener = (OnRefreshState1Listener) context;
        } catch (ClassCastException ignored) {
        }
    }


    @Override
    protected SimbaState1FragmentBinding initViewBinding(LayoutInflater inflater, ViewGroup container) {
        return SimbaState1FragmentBinding.inflate(inflater);
    }

    @Override
    protected void initView() {

        mActivity = (BaseActivity<ViewBinding>) getActivity();

        mActivity.setStatusBarHeight(binding.tvRoot);

        binding.getRoot().setPadding(0, 0, 0, 0);

        binding.refresh.setOnRefreshListener(() -> {
            PU.userBuriedPoint(PU.P194, "");
            loadData();
            if (mOnRefreshDataFragmentListener != null) {
                mOnRefreshDataFragmentListener.onLoadData();
            }
        });
        binding.tvBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (binding.tvBtn.isSelected() && productsAmount != null) {
                    ViewUtils.viewScale(v);
                    PU.userBuriedPoint(PU.P189, "");
                    toApply(true, "", "", productsAmount.getAmount());
                }
            }
        });

        binding.tvCs.setOnClickListener(v -> {
            ViewUtils.viewScale(v);
            PU.userBuriedPoint(PU.P190, "");
            startActivity(new Intent(getActivity(), SimbaCustomerServiceActivity.class));
        });


    }

    @Override
    protected void initData() {
        UP_TYPE1 = PU.P187;
        UP_TYPE2 = PU.P188;
        setAmoutData();
    }

    @Override
    public void onResume() {
        super.onResume();
        loadData();
    }

    void loadData() {
        getHomePage();
    }

    @SuppressLint("SetTextI18n")
    void setAmoutData() {
        if (getActivity() != null) {
            binding.refresh.setRefreshing(false);
            if (productsAmount != null) {
                binding.tvAmount.setText(productsAmount.getAmount());
                binding.tvBtn.setSelected(NumUtils.str2Double(productsAmount.getAmount()) > 0);
                SpUtils.save_string(getActivity(), SpUtils.KEY_CASH_AMOUNT, productsAmount.getAmount());
            }
        }
    }

    void getHomePage() {
        if (binding != null && mActivity != null) {
            String token = SpUtils.get_string(getContext(), SpUtils.KEY_TOKEN, "");
            JsonObject json = BaseParams.getJsonObject(getContext(), PathMaping.PathList[9], U.URL_MAIN_PRODUCT, token);
            HashMap<String, String> heads = new HashMap<>();
            heads.put("product", U.URL_MAIN_PRODUCT);
            if (!TextUtils.isEmpty(U.URL_COUNTRY)) {
                heads.put("country", U.URL_COUNTRY);
            }
            LogUtil.e("me", "getHomePage post->" + json);
            mActivity.showLoading("");
            RxHttp.post(U.commonUrl, AESCryptUtilJar.encryptDefault(json.toString()), heads)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<>() {
                        @Override
                        public void onSubscribe(@NonNull Disposable d) {

                        }

                        @Override
                        public void onNext(@NonNull String s) {
                            if (binding != null && mActivity != null) {
                                mActivity.hideLoading();
                                if (!TextUtils.isEmpty(s)) {
                                    String json1 = AESCryptUtilJar.decryptDefault(s);
                                    LogUtil.e("me", "getHomePage json->" + json1);
                                    if (JsonParse.getCode(json1)) {
                                        productsAmount = JsonParse.loanLimitJson2Obj(json1);
                                        setAmoutData();
                                    } else {
                                        mActivity.showFailedDialog(new BaseDialog.BtnClickListener() {
                                            @Override
                                            public void btnOnClickOk() {
                                                loadData();
                                            }

                                            @Override
                                            public void btnOnClickCancel() {

                                            }

                                            @Override
                                            public void btnOnClickColse() {

                                            }
                                        });
                                    }
                                }
                            }
                        }

                        @Override
                        public void onError(@NonNull Throwable e) {
                            if (e != null) {
                                LogUtil.e("me", "getHomePage e->" + e);
                            }
                            if (binding != null && mActivity != null) {
                                mActivity.showFailedDialog(new BaseDialog.BtnClickListener() {
                                    @Override
                                    public void btnOnClickOk() {
                                        loadData();
                                    }

                                    @Override
                                    public void btnOnClickCancel() {

                                    }

                                    @Override
                                    public void btnOnClickColse() {

                                    }
                                });
                            }
                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        }
    }


    void toApply(boolean isApply, String orderId, String state, String amount) {

        if (getContext() != null) {
            boolean isAllPermissionsGranted = true;
            if (SimbaApp.getInstance().getAppInfo() != null && SimbaApp.getInstance().getAppInfo().getPermission() != null) {
                for (String permission : SimbaApp.getInstance().getAppInfo().getPermission()) {
                    if (permission.equals("android.permission.READ_SMS") && ContextCompat.checkSelfPermission(getContext(), permission) != PackageManager.PERMISSION_GRANTED) {
                        isAllPermissionsGranted = false;
                        break;
                    }
                }
            }

            SpUtils.save_string(getContext(), SpUtils.KEY_CASH_AMOUNT, amount);
            LogUtil.e("me", "amount->" + amount);

            if (isAllPermissionsGranted) {
                PU.userBuriedAllPoint(getActivity());
                PU.sendDevice();
                String token = SpUtils.get_string(getActivity(), SpUtils.KEY_TOKEN, "");
                if (mActivity != null) {
                    mActivity.userProcess(token, () -> {
                        boolean isCheckSteps = mActivity.checkSteps();
                        if (!isCheckSteps) {
                            if (isApply) {
                                startActivity(new Intent(getActivity(), SimbaApplyActivity.class));
                            }
                        }
                    }, true);
                }
            } else {
                startActivity(new Intent(getContext(), SimbaPermissionDesActivity.class));
            }
        }

    }


    public interface OnRefreshState1Listener {
        void onLoadData();
    }

}
